<?php
/**
 * swoole websocket服务
 * @author chendanming@star-net.cn
 * @copyright  ktvme. All Rights Reserved.
 * @version $Id: Server.php 629 2018-05-08 08:14:13Z chendanming $
 */

namespace app\console\socket;

use app\common\console\Command;
use think\console\Input;
use think\console\Output;
use think\Config;
use think\Log;
use app\console\socket\logic\Game;

class WebsocketServer extends Command {
    private $game;
    private $server;

    protected function configure() {
        $this->setName('bengben-swoole-websocket-service')->setDescription('swoole websocket服务');
    }

    protected function execute(Input $input, Output $output) {
        $sllConfig = Config::get('ssl');
        $socketConfig = Config::get('websocket');
        $address = $socketConfig['address'];
        $port = $socketConfig['port'];
        $this->server = new \swoole_websocket_server($address, $port,SWOOLE_BASE,SWOOLE_SOCK_TCP | SWOOLE_SSL);
        $this->server->set($sllConfig);
        $this->game = new Game($this->server);

        $this->server->on('open', function (\swoole_websocket_server $server, $request) {
            echo "client {$request->fd} connect\n";
        });

        $this->server->on('message', function (\swoole_websocket_server $server, $frame) {
            //$this->server->push($frame->fd,'123');
            $this->game->event($frame->data, $frame->fd, $frame->fd);
        });

        $this->server->on('close', function ($ser, $fd) {
            echo "client $fd lost\n";
            $this->game->event('{"type":"leaveRoom"}', $fd, $fd);
        });

        $this->server->start();
    }

}